package fat3kb.everything.dao.hibernate;

import fat3kb.everything.model.Dish;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: antonbern
 * Date: 09.10.2007
 * Time: 13:36:56
 * To change this template use File | Settings | File Templates.
 */
public class DishDAOImpl implements DishDAO {

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	private HibernateTemplate hibernateTemplate;

	public Dish getDish(final String id) {
		return (Dish) hibernateTemplate.execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				return session.get(Dish.class, id);
			}
		});
	}

	public void save(final Dish dish) {
		hibernateTemplate.execute(new HibernateCallback() {

			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				return session.save(dish);
			}
		});
	}

	public void printAll() {
		List<Dish> dishes = (List<Dish>) hibernateTemplate.execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				String selectQuery = "select dish from Dish as dish";
				Query query = session.createQuery(selectQuery);
				return query.list();
			}
		});
		for (Dish dish : dishes) {
			System.out.println(dish.getId());
			System.out.println(dish.getName());
			System.out.println(dish.getPrice());
			System.out.println(dish.getWeight());
			System.out.println();
		}
	}
}
